﻿using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CastingWellEquipmentGUI.ViewModel.Pages.SettingMenuPages
{
    public class RecipeTagSettingPageViewModel : ViewModelBase
    {

        /// <summary>
        /// 搜索条件
        /// </summary>
        private Meta_Tag _SeachModel = new Meta_Tag();
        /// <summary>
        /// 搜索条件
        /// </summary>
        public Meta_Tag SeachModel
        {
            get { return _SeachModel; }
            set { _SeachModel = value; }
        }

        private string SelectModel = "";
        /// <summary>
        /// 更改标签命令
        /// </summary>
        public DelegateCommand ChangeTagValueCommand { get; set; }

        private RecipeSelection _SelectTag;
        public RecipeSelection SelectTag
        {
            get { return _SelectTag; }
            set
            {
                _SelectTag = value;
                RaisePropertyChanged("SelectTag");
            }
        }


        private RecipeSelection _AcceptedTag;
        public RecipeSelection AcceptedTag
        {
            get { return _AcceptedTag; }
            set
            {
                _AcceptedTag = value;
                RaisePropertyChanged("AcceptedTag");
            }
        }
        private RecipeSelection _InputNormalTag;
        public RecipeSelection InputNormalTag
        {
            get { return _InputNormalTag; }
            set
            {
                _InputNormalTag = value;
                RaisePropertyChanged("InputNormalTag");
            }
        }
        private RecipeSelection _RecipeEffectiveTag;
        public RecipeSelection RecipeEffectiveTag
        {
            get { return _RecipeEffectiveTag; }
            set
            {
                _RecipeEffectiveTag = value;
                RaisePropertyChanged("RecipeEffectiveTag");
            }
        }



        private ObservableCollection<ControlTag> _PlcModels;
        public ObservableCollection<ControlTag> PlcModels
        {
            get { return _PlcModels; }
            set
            {
                _PlcModels = value;

                RaisePropertyChanged("PlcModels");
            }
        }
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        private ControlTag _SelectPlcModel;
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        public ControlTag SelectPlcModel
        {
            get { return _SelectPlcModel; }
            set
            {
                _SelectPlcModel = value;
                if (IsChangeTagValue == false && _SelectPlcModel != null)
                {
                    RefreshTagModels();
                }
                RaisePropertyChanged("SelectPlcModel");
            }
        }

        private ObservableCollection<ControlTag> _TagModels;

        public ObservableCollection<ControlTag> TagModels
        {
            get { return _TagModels; }
            set
            {
                _TagModels = value;
                RaisePropertyChanged("TagModels");
            }
        }

        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        private ControlTag _SelectTagModel;
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        public ControlTag SelectTagModel
        {
            get { return _SelectTagModel; }
            set
            {
                _SelectTagModel = value;
                RaisePropertyChanged("SelectTagModel");
            }
        }
        #region 分页使用
        /// <summary>
        /// 每页数量
        /// </summary>
        private int itemCount = 5;

        /// <summary>
        /// 总数量
        /// </summary>
        private int totalDataCount = 0;

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPageNumber
        {
            get
            {
                int totalPageNumber = totalDataCount / itemCount;
                if (totalDataCount % itemCount > 0)
                {
                    totalPageNumber++;
                }
                return totalPageNumber;

            }
        }
        /// <summary>
        /// 总数据量
        /// </summary>
        public int TotalDataCount
        {
            get { return totalDataCount; }
            set
            {
                totalDataCount = value;
                RaisePropertyChanged("TotalDataCount");
                RaisePropertyChanged("TotalPageNumber");
            }
        }

        /// <summary>
        /// 当前所在页数
        /// </summary>
        private int _CurrentPageNumber = 1;
        /// <summary>
        /// 当前所在页数
        /// </summary>
        public int CurrentPageNumber
        {
            get { return _CurrentPageNumber; }
            set
            {
                _CurrentPageNumber = value;
                RaisePropertyChanged("CurrentPageNumber");
            }
        }
        /// <summary>
        /// 上一页页数
        /// </summary>
        public int PreviousPageNumber
        {
            get
            {
                if (_CurrentPageNumber - 1 > 0)
                {
                    return _CurrentPageNumber - 1;
                }
                return 1;
            }

        }
        /// <summary>
        /// 下一页页数
        /// </summary>
        public int NextPageNumber
        {
            get
            {
                if (_CurrentPageNumber + 1 <= TotalPageNumber)
                {
                    return _CurrentPageNumber + 1;
                }
                return _CurrentPageNumber;
            }

        }

        /// <summary>
        /// 选中的项目
        /// </summary>
        private RecipeVerificationConfig _SelectedItemModel;
        /// <summary>
        /// 选中的项目
        /// </summary>
        public RecipeVerificationConfig SelectedItemModel
        {
            get { return _SelectedItemModel; }
            set
            {
                _SelectedItemModel = value;

                RaisePropertyChanged("SelectedItemModel");
            }
        }

        /// <summary>
        /// 分页页码集合
        /// </summary>
        private ObservableCollection<PageNumerModel> _PageNumers = new ObservableCollection<PageNumerModel>();
        /// <summary>
        /// 分页页码集合
        /// </summary>
        public ObservableCollection<PageNumerModel> PageNumers
        {
            get => _PageNumers;
            set
            {
                _PageNumers = value;
                RaisePropertyChanged("PageNumers");
            }
        }
        /// <summary>
        /// 跳转到指定页面命令
        /// </summary>
        public DelegateCommand GoToPageByNumberCommand { get; set; }
        /// <summary>
        /// 跳转到指定页面并关闭AllPageNumberPanel窗体命令
        /// </summary>
        public DelegateCommand GoToPageByNumberAndCloseAllPageNumberPanelCommand { get; set; }


        #endregion 分页使用

        public DelegateCommand SaveAndHideCommand { get; set; }

        public DelegateCommand ShowEditModelCommand { get; set; }
        public DelegateCommand ShowEditDataModelCommand { get; set; }
        public DelegateCommand ShowStorageDataModelCommand { get; set; }

        public DelegateCommand HideControlTagEditWindowCommand { get; set; }

        public DelegateCommand SearchCommand { get; set; }

        /// <summary>
        /// 主列表数据
        /// </summary>
        private ObservableCollection<RecipeVerificationConfig> _DataCollection;
        /// <summary>
        /// 主列表数据
        /// </summary>
        public ObservableCollection<RecipeVerificationConfig> DataCollection
        {
            get { return _DataCollection; }
            set
            {
                _DataCollection = value;
                RaisePropertyChanged("DataCollection");
            }
        }

        private void SaveAndHideHandler(object obj)
        {
            string sql = "";
            RecipeVerificationConfig QueryModel = null;
            if (IsChangeTagValue == false)
            {
                if (SelectModel == "验证")
                {
                    QueryModel = new RecipeVerificationConfig
                    {
                        Id = SelectedItemModel.Id,
                        TagId = SelectTagModel.TagID
                    };
                    sql = @"UPDATE RecipeVerificationConfig 
                        SET TagId = @TagId
                        WHERE Id = @Id";
                }
                else if (SelectModel == "数据")
                {
                    QueryModel = new RecipeVerificationConfig
                    {
                        Id = SelectedItemModel.Id,
                        DataTagId = SelectTagModel.TagID
                    };
                    sql = @"UPDATE RecipeVerificationConfig 
                        SET DataTagId = @DataTagId
                        WHERE Id = @Id";
                }
                else if (SelectModel == "存储")
                {
                    QueryModel = new RecipeVerificationConfig
                    {
                        Id = SelectedItemModel.Id,
                        StorageTagId = SelectTagModel.TagID
                    };
                    sql = @"UPDATE RecipeVerificationConfig 
                        SET StorageTagId = @StorageTagId
                        WHERE Id = @Id";
                }
                DapperToolsThisSystem.Update<RecipeVerificationConfig>(sql, QueryModel);
            }
            else
            {

                SelectTag.RecipeSelectionTagId = SelectTagModel.TagID;
                sql = @"UPDATE RecipeSelection
                        SET RecipeSelectionTagId = @RecipeSelectionTagId
                        WHERE RecipeSelectionId = @RecipeSelectionId";
                DapperToolsThisSystem.Update(sql, SelectTag);
                IsChangeTagValue = false;
            }
            InitDataCollection();
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideRecipeTagEditWindow"));
        }
        private void HideControlTagEditWindowHandler(object obj)
        {
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideRecipeTagEditWindow"));
        }
        private void ShowEditModelHandler(object obj)
        {
            if (SelectedItemModel != null)
            {
                SelectPlcModel = null;
                if (SelectModel == "验证")
                {
                    for (int i = 0; i < PlcModels.Count; i++)
                    {
                        if (PlcModels[i].BrandName == SelectedItemModel.BrandName &&
                            PlcModels[i].PlcModelName == SelectedItemModel.PlcModelName)
                        {
                            SelectPlcModel = PlcModels[i];
                            break;
                        }
                    }
                }
                else if (SelectModel == "数据")
                {
                    for (int i = 0; i < PlcModels.Count; i++)
                    {
                        if (PlcModels[i].BrandName == SelectedItemModel.DataTagBrandName &&
                            PlcModels[i].PlcModelName == SelectedItemModel.DataTagPlcModelName)
                        {
                            SelectPlcModel = PlcModels[i];
                            break;
                        }
                    }
                }
                else if (SelectModel == "存储")
                {
                    for (int i = 0; i < PlcModels.Count; i++)
                    {
                        if (PlcModels[i].BrandName == SelectedItemModel.DataTagBrandName &&
                            PlcModels[i].PlcModelName == SelectedItemModel.DataTagPlcModelName)
                        {
                            SelectPlcModel = PlcModels[i];
                            break;
                        }
                    }
                }
                if (SelectPlcModel == null)
                {
                    SelectPlcModel = PlcModels[0];
                }
                SelectModel = "验证";
                RefreshTagModels();
                WindowManager.ShowDialog("RecipeTagEditWindow", null);
            }
            else
            {
                MessageBox.Show("请选择要编辑的校验项！");
            }

        }
        private void ShowEditModeDatalHandler(object obj)
        {
            if (SelectedItemModel != null)
            {
                SelectPlcModel = null;
                for (int i = 0; i < PlcModels.Count; i++)
                {
                    if (PlcModels[i].BrandName == SelectedItemModel.DataTagBrandName &&
                        PlcModels[i].PlcModelName == SelectedItemModel.DataTagPlcModelName)
                    {
                        SelectPlcModel = PlcModels[i];
                        break;
                    }
                }
                if (SelectPlcModel == null)
                {
                    SelectPlcModel = PlcModels[0];
                }
                SelectModel = "数据";
                RefreshTagModels();

                WindowManager.ShowDialog("RecipeTagEditWindow", null);
            }
            else
            {
                MessageBox.Show("请选择要编辑的数据项！");
            }

        }

        private void ShowStorageDataModelHandler(object obj)
        {
            if (SelectedItemModel != null)
            {
                SelectPlcModel = null;
                for (int i = 0; i < PlcModels.Count; i++)
                {
                    if (PlcModels[i].BrandName == SelectedItemModel.DataTagBrandName &&
                        PlcModels[i].PlcModelName == SelectedItemModel.DataTagPlcModelName)
                    {
                        SelectPlcModel = PlcModels[i];
                        break;
                    }
                }
                if (SelectPlcModel == null)
                {
                    SelectPlcModel = PlcModels[0];
                }
                SelectModel = "存储";
                RefreshTagModels();

                WindowManager.ShowDialog("RecipeTagEditWindow", null);
            }
            else
            {
                MessageBox.Show("请选择要编辑的存储项！");
            }

        }

        private void RefreshTagModels()
        {
            string sql = @"SELECT 
                            Meta_Tag.TagID,
                            Meta_Tag.TagName,
                            Meta_Tag.Address, 
                            Meta_Tag.DataType
                           FROM DB_AlarmServer.dbo.Meta_Tag 
                           INNER JOIN DB_AlarmServer.dbo.Meta_Group ON Meta_Tag.GroupID = Meta_Group.GroupID
                           INNER JOIN DB_AlarmServer.dbo.Meta_Driver ON Meta_Driver.DriverID = Meta_Group.DriverID 
                           INNER JOIN DB_AlarmServer.dbo.PlcModel ON PlcModel.PlcModelId = Meta_Driver.PlcModelId 
                           INNER JOIN DB_AlarmServer.dbo.Brand ON Brand.BrandId = PlcModel.BrandId 
                           WHERE PlcModel.PlcModelName = '" + SelectPlcModel.PlcModelName + @"' 
                           AND Brand.BrandName = '" + SelectPlcModel.BrandName + @"'";
            if (SeachModel.TagName != null && SeachModel.TagName != "" && !XyhUtils.IsHasSQLInject(SeachModel.TagName))
            {
                sql += @" AND Meta_Tag.TagName LIKE '%" + SeachModel.TagName + "%'";
            }
            if (SeachModel.Address != null && SeachModel.Address != "" && !XyhUtils.IsHasSQLInject(SeachModel.Address))
            {
                sql += @" AND Meta_Tag.Address LIKE '%" + SeachModel.Address + "%'";
            }
            sql += @" ORDER BY Meta_Tag.TagName";
            TagModels = DapperToolsThisSystem.QueryOc<ControlTag>(sql);
            for (int i = 0; i < TagModels.Count; i++)
            {
                if (TagModels[i].TagID == SelectedItemModel.TagId)
                {
                    SelectTagModel = TagModels[i];
                    break;
                }
            }
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "TagScrollIntoView"));
        }
        /// <summary>
        /// 跳转到指定页面命令的处理器
        /// </summary>
        /// <param name="obj"></param>
        private void GoToPageByNumberHandler(object obj)
        {
            switch (obj.ToString())
            {
                case "PreviousPage":
                    CurrentPageNumber = PreviousPageNumber;
                    break;
                case "NextPage":
                    CurrentPageNumber = NextPageNumber;
                    break;
                case "FirstPage":
                    CurrentPageNumber = 1;
                    break;
                case "LastPage":
                    CurrentPageNumber = TotalPageNumber;
                    break;
                default:
                    CurrentPageNumber = int.Parse(obj.ToString());
                    break;
            }
            InitDataCollection();
        }
        /// <summary>
        /// 跳转到更改页码的列表
        /// </summary>
        /// <param name="obj"></param>
        private void GoToPageByNumberAndCloseAllPageNumberPanelHandler(object obj)
        {
            GoToPageByNumberHandler(obj);
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideAllPageNumberPanelForRecipeManage"));
        }
        /// <summary>
        /// 初始化主列表数据
        /// </summary>
        private void InitDataCollection()
        {
            string baseSearchSql = @"SELECT ROW_NUMBER() OVER (
                                                                ORDER BY RecipeVerificationConfig.Id
                                                               ) as rownumber,
                                            RecipeVerificationConfig.Id,
                                            RecipeVerificationConfig.ItemName,
                                            RecipeVerificationConfig.ItemExplain,
                                            VerificationTag.TagID,
                                            VerificationTag.TagName,
                                            VerificationTag.Address,
                                            VerificationPlcModel.PlcModelName,
                                            VerificationBrand.BrandName,

                                            DataTag.TagID AS DataTagId,
                                            DataTag.TagName AS DataTagName,
                                            DataTag.Address AS DataTagAddress,
                                            DataPlcModel.PlcModelName AS DataTagPlcModelName,
                                            DataBrand.BrandName AS DataTagBrandName,

                                            StorageTag.TagID AS StorageTagId,
                                            StorageTag.TagName AS StorageTagName,
                                            StorageTag.Address AS StorageTagAddress,
                                            StoragePlcModel.PlcModelName AS StorageTagPlcModelName,
                                            StorageBrand.BrandName AS StorageTagBrandName

                                            from DB_CWEGUI.dbo.RecipeVerificationConfig 
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Tag VerificationTag ON VerificationTag.TagID = RecipeVerificationConfig.TagId
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Group VerificationGroup ON VerificationGroup.GroupID = VerificationGroup.GroupID
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Driver VerificationDriver ON VerificationDriver.DriverID = VerificationGroup.DriverID
                                            LEFT JOIN DB_AlarmServer.dbo.PlcModel VerificationPlcModel ON VerificationPlcModel.PlcModelId = VerificationDriver.PlcModelId
                                            LEFT JOIN DB_AlarmServer.dbo.Brand VerificationBrand ON VerificationBrand.BrandId = VerificationPlcModel.BrandId 
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Tag DataTag ON DataTag.TagID = RecipeVerificationConfig.DataTagId
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Group DataGroup ON DataGroup.GroupID = DataTag.GroupID
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Driver DataDriver ON DataDriver.DriverID = DataGroup.DriverID
                                            LEFT JOIN DB_AlarmServer.dbo.PlcModel DataPlcModel ON DataPlcModel.PlcModelId = DataDriver.PlcModelId
                                            LEFT JOIN DB_AlarmServer.dbo.Brand DataBrand ON DataBrand.BrandId = DataPlcModel.BrandId

                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Tag StorageTag ON StorageTag.TagID = RecipeVerificationConfig.StorageTagId
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Group StorageGroup ON StorageGroup.GroupID = StorageTag.GroupID
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Driver StorageDriver ON StorageDriver.DriverID = StorageGroup.DriverID
                                            LEFT JOIN DB_AlarmServer.dbo.PlcModel StoragePlcModel ON StoragePlcModel.PlcModelId = StorageDriver.PlcModelId
                                            LEFT JOIN DB_AlarmServer.dbo.Brand StorageBrand ON StorageBrand.BrandId = StoragePlcModel.BrandId
                                            WHERE 1 = 1 
                                            
                                            ";

            baseSearchSql += @" GROUP BY RecipeVerificationConfig.Id,
                                            RecipeVerificationConfig.ItemName,
                                            RecipeVerificationConfig.ItemExplain,
                                            VerificationTag.TagID,
                                            VerificationTag.TagName,
                                            VerificationTag.Address,
                                            VerificationPlcModel.PlcModelName,
                                            VerificationBrand.BrandName,
                                            DataTag.TagID,
                                            DataTag.TagName,
                                            DataTag.Address,
                                            DataPlcModel.PlcModelName,
                                            DataBrand.BrandName,
                                            StorageTag.TagID,
                                            StorageTag.TagName,
                                            StorageTag.Address,
                                            StoragePlcModel.PlcModelName,
                                            StorageBrand.BrandName";
            string pageingSql = @"SELECT TOP " + itemCount + @" * 
                                  FROM (" + baseSearchSql + @") temp_row
                                  WHERE rownumber > ((" + CurrentPageNumber + @" - 1 ) * " + itemCount + @" ); ";
            DataCollection = DapperToolsThisSystem.QueryOc<RecipeVerificationConfig>(pageingSql);
            //总数据量
            TotalDataCount = DapperToolsThisSystem.GetCount(baseSearchSql);
            for (int i = 0; i < DataCollection.Count; i++)
            {
                DataCollection[i].OrderNo = (i + 1 + ((CurrentPageNumber - 1) * itemCount));
            }
            RecipeSelection InputNormalTagWhere = new RecipeSelection
            {
                RecipeSelectionName = "输入正常"
            };
            InputNormalTag = DapperToolsThisSystem.Query("select a.*,b.TagName AS RecipeSelectionTagName from RecipeSelection a left join DB_AlarmServer.dbo.Meta_Tag b on a.RecipeSelectionTagId = b.TagID  where a.RecipeSelectionName = @RecipeSelectionName ", InputNormalTagWhere);

            RecipeSelection RecipeEffectiveTagWhere = new RecipeSelection
            {
                RecipeSelectionName = "配方有效"
            };
            RecipeEffectiveTag = DapperToolsThisSystem.Query("select a.*,b.TagName AS RecipeSelectionTagName from RecipeSelection a left join DB_AlarmServer.dbo.Meta_Tag b on a.RecipeSelectionTagId = b.TagID  where a.RecipeSelectionName = @RecipeSelectionName ", RecipeEffectiveTagWhere);
            RecipeSelection AcceptedTagWhere = new RecipeSelection
            {
                RecipeSelectionName = "已接受"
            };
            AcceptedTag = DapperToolsThisSystem.Query("select a.*,b.TagName AS RecipeSelectionTagName from RecipeSelection a left join DB_AlarmServer.dbo.Meta_Tag b on a.RecipeSelectionTagId = b.TagID  where a.RecipeSelectionName = @RecipeSelectionName ", AcceptedTagWhere);
            
        }

        private void InitPlcModels()
        {
            PlcModels = DapperToolsThisSystem.QueryOc<ControlTag>("SELECT Brand.BrandName,PlcModel.PlcModelName FROM DB_AlarmServer.dbo.PlcModel LEFT JOIN DB_AlarmServer.dbo.Brand ON PlcModel.BrandId = Brand.BrandId ORDER BY Brand.BrandId");
        }

        private bool IsChangeTagValue = false;


        private void ChangeTagValueHandler(object obj)
        {
            if (obj != null)
            {
                IsChangeTagValue = true;
                RecipeSelection recipeSelectionWhere = new RecipeSelection();
                recipeSelectionWhere.RecipeSelectionId = int.Parse(obj.ToString());
                string sql = @"SELECT * FROM RecipeSelection WHERE RecipeSelectionId = @RecipeSelectionId";
                RecipeSelection recipeSelection = DapperToolsThisSystem.Query(sql, recipeSelectionWhere);
                SelectTag = recipeSelection;
                ControlTag controlTagWhere = new ControlTag
                {
                    TagID = recipeSelection.RecipeSelectionTagId
                };
                sql = @"SELECT 
                           Meta_Tag.TagID,
                           Brand.BrandName,
                           PlcModel.PlcModelName 
                      FROM DB_AlarmServer.dbo.Meta_Tag
                      LEFT JOIN DB_AlarmServer.dbo.Meta_Group ON Meta_Tag.GroupID =Meta_Group.GroupID     
                      LEFT JOIN DB_AlarmServer.dbo.Meta_Driver ON Meta_Driver.DriverID=Meta_Group.DriverID
                      LEFT JOIN DB_AlarmServer.dbo.PlcModel ON Meta_Driver.PlcModelId=PlcModel.PlcModelId
                      LEFT JOIN DB_AlarmServer.dbo.Brand ON PlcModel.BrandId = Brand.BrandId
                      WHERE Meta_Tag.TagID = @TagID
                      ORDER BY Brand.BrandId";
                ControlTag selectPlcModelt = DapperToolsGatewayServer.Query(sql, controlTagWhere);
                SelectPlcModel = selectPlcModelt;
                SelectModel = "数据";
                if (SelectPlcModel != null)
                {
                    sql = @"SELECT 
                            Meta_Tag.TagID,
                            Meta_Tag.TagName,
                            Meta_Tag.Address, 
                            Meta_Tag.DataType
                           FROM DB_AlarmServer.dbo.Meta_Tag 
                           INNER JOIN DB_AlarmServer.dbo.Meta_Group ON Meta_Tag.GroupID = Meta_Group.GroupID
                           INNER JOIN DB_AlarmServer.dbo.Meta_Driver ON Meta_Driver.DriverID = Meta_Group.DriverID 
                           INNER JOIN DB_AlarmServer.dbo.PlcModel ON PlcModel.PlcModelId = Meta_Driver.PlcModelId 
                           INNER JOIN DB_AlarmServer.dbo.Brand ON Brand.BrandId = PlcModel.BrandId 
                           WHERE PlcModel.PlcModelName = '" + SelectPlcModel.PlcModelName + @"' 
                           AND Brand.BrandName = '" + SelectPlcModel.BrandName + @"' 
                           ORDER BY Meta_Tag.TagName";
                    TagModels = DapperToolsThisSystem.QueryOc<ControlTag>(sql);
                    for (int i = 0; i < TagModels.Count; i++)
                    {
                        if (TagModels[i].TagID == controlTagWhere.TagID)
                        {
                            SelectTagModel = TagModels[i];
                            break;
                        }
                    }
                }
                else {
                    sql = @"SELECT 
                            Meta_Tag.TagID,
                            Meta_Tag.TagName,
                            Meta_Tag.Address, 
                            Meta_Tag.DataType
                           FROM DB_AlarmServer.dbo.Meta_Tag 
                           INNER JOIN DB_AlarmServer.dbo.Meta_Group ON Meta_Tag.GroupID = Meta_Group.GroupID
                           INNER JOIN DB_AlarmServer.dbo.Meta_Driver ON Meta_Driver.DriverID = Meta_Group.DriverID 
                           INNER JOIN DB_AlarmServer.dbo.PlcModel ON PlcModel.PlcModelId = Meta_Driver.PlcModelId 
                           INNER JOIN DB_AlarmServer.dbo.Brand ON Brand.BrandId = PlcModel.BrandId 
                           ORDER BY Meta_Tag.TagName";
                    TagModels = DapperToolsThisSystem.QueryOc<ControlTag>(sql);
                    SelectTagModel = TagModels[0];
                }
                
           
                Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "TagScrollIntoView"));
                WindowManager.ShowDialog("RecipeTagEditWindow", null);
            }
        }

        public void SearchHandler(object obj)
        {
            RefreshTagModels();
        }

        public RecipeTagSettingPageViewModel()
        {
            InitPlcModels();
            InitDataCollection();
            GoToPageByNumberCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(GoToPageByNumberHandler)
            };
            GoToPageByNumberAndCloseAllPageNumberPanelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(GoToPageByNumberAndCloseAllPageNumberPanelHandler)
            };
            ShowEditModelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ShowEditModelHandler)
            };
            ShowEditDataModelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ShowEditModeDatalHandler)
            };
            ShowStorageDataModelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ShowStorageDataModelHandler)
            };
            HideControlTagEditWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideControlTagEditWindowHandler)
            };
            SaveAndHideCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SaveAndHideHandler)
            };
            ChangeTagValueCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ChangeTagValueHandler)
            };
            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };
        }
    }
}
